package com.example.mycarcalling.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.example.lib_cache.adapter.PoiAdapter;
import com.example.lib_cache.dao.OnPoiNameClickListener;
import com.example.lib_cache.viewmodel.StartActivityViewModel;
import com.example.mycarcalling.R;
import com.example.mycarcalling.databinding.ActivityStartBinding;

import java.lang.reflect.Method;
import java.util.List;

import static android.os.Build.VERSION.SDK_INT;

public class StartActivity extends AppCompatActivity implements OnGetPoiSearchResultListener, OnGetSuggestionResultListener {

    private ActivityStartBinding activityStartBinding;
    private StartActivityViewModel startActivityViewModel;
    public final static String TAG = StartActivity.class.getSimpleName();

    private PoiSearch mPoiSearch;
    private SuggestionSearch mSuggestionSearch;

    private PoiAdapter poiAdapter = null;

    private int mLoadIndex;
    private int scope;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityStartBinding = DataBindingUtil
                .setContentView(this,R.layout.activity_start);

        initView();
        initData();
        initListener();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(null != mPoiSearch){
            mPoiSearch.destroy();
        }

        if(null != mSuggestionSearch){
            mSuggestionSearch.destroy();
        }
    }

    private void initView(){
        setTitle("设置起点");
        LinearLayoutManager llm = new LinearLayoutManager(this);
        activityStartBinding.rvPoiItem.setLayoutManager(llm);

        poiAdapter = new PoiAdapter();
        activityStartBinding.rvPoiItem.setAdapter(poiAdapter);

    }

    private void initListener(){
        mPoiSearch.setOnGetPoiSearchResultListener(this);

        mSuggestionSearch.setOnGetSuggestionResultListener(this);

        activityStartBinding.etSelectDes.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                selectCity();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });



        activityStartBinding.rvPoiItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        poiAdapter.setOnPoiNameClickListener(new OnPoiNameClickListener() {
            @Override
            public void finishThisActivity() {
                setResult(1);
                finish();
            }
        });




//        activityStartBinding.etSelectDes
//                .setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
////                selectCity();
////                Log.d("文本改变",v.getText().toString());
//                return false;
//            }
//        });
    }

    private void initData(){

//        if (SDK_INT < Build.VERSION_CODES.P) {
//            return;
//        }
//        try {
//            Method forName = Class.class.getDeclaredMethod("forName", String.class);
//            Method getDeclaredMethod = Class.class.getDeclaredMethod("getDeclaredMethod", String.class, Class[].class);
//            Class<?> vmRuntimeClass = (Class<?>) forName.invoke(null, "dalvik.system.VMRuntime");
//            Method getRuntime = (Method) getDeclaredMethod.invoke(vmRuntimeClass, "getRuntime", null);
//            Method setHiddenApiExemptions = (Method) getDeclaredMethod.invoke(vmRuntimeClass, "setHiddenApiExemptions", new Class[]{String[].class});
//            Object sVmRuntime = getRuntime.invoke(null);
//            setHiddenApiExemptions.invoke(sVmRuntime, new Object[]{new String[]{"L"}});
//        } catch (Throwable e) {
//            Log.e("[error]", "reflect bootstrap failed:", e);
//        }

        //创建数据源
        //创建一个ViewModel的工厂
        ViewModelProvider.Factory factory = ViewModelProvider.
                AndroidViewModelFactory.getInstance(getApplication());
        //创建ViewModel的管理对象
        ViewModelProvider viewModelProvider = new ViewModelProvider(this,factory);
        //生产ViewModel
        startActivityViewModel = viewModelProvider.
                get(StartActivityViewModel.class);

        mPoiSearch = PoiSearch.newInstance();
        mSuggestionSearch = SuggestionSearch.newInstance();


        startActivityViewModel.loadingData();
        activityStartBinding.setStartMapCity(startActivityViewModel);
        activityStartBinding.setLifecycleOwner(this);

    }

    /**
     * 发起请求
     */
    private void selectCity(){
        // 发起请求
        String keywordStr = activityStartBinding.etSelectDes
                .getText().toString().trim();
        if(TextUtils.isEmpty(keywordStr)){
            return;
        }
        Log.d(TAG,keywordStr);
        mLoadIndex = 10;
        scope = 2;
        mPoiSearch.searchInCity((new PoiCitySearchOption())
                .city(activityStartBinding.tvStartCity.getText().toString().trim())
                .keyword(keywordStr)
                .pageNum(mLoadIndex) // 分页编号
                .cityLimit(true)
                .scope(scope));

        mSuggestionSearch.requestSuggestion(new SuggestionSearchOption()
                .city(activityStartBinding.tvStartCity.getText().toString().trim())
                .keyword(keywordStr));

    }

    @Override
    public void onGetPoiResult(PoiResult poiResult) {
        if (poiResult == null || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
//            Toast.makeText(StartActivity.this,
//                    "未找到结果", Toast.LENGTH_LONG).show();
            return;
        }

        List<PoiInfo> poiInfos = poiResult.getAllPoi();
        if (null == poiInfos) {
            return;
        }
        Log.d(TAG,String.valueOf("poiResult"+poiInfos.size()));

        // 隐藏之前的
//        hidePoiInfoLayout();

//        mRecyclerView.setVisibility(View.VISIBLE);
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    @Override
    public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {

    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    @Override
    public void onGetSuggestionResult(SuggestionResult suggestionResult) {
        if(null == suggestionResult
                || suggestionResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND){
            mLoadIndex = 0;
            Toast.makeText(StartActivity.this,"未找到地点",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        Toast.makeText(StartActivity.this,"已找到地点",
                Toast.LENGTH_SHORT).show();
        List<SuggestionResult.SuggestionInfo> suggestionInfos
                = suggestionResult.getAllSuggestions();
        if(null == suggestionInfos){
            Log.d("得到推荐1",suggestionInfos.toString());

            return;
        }
        Log.d(TAG,String.valueOf("Suggestion"+suggestionInfos.size()));

        activityStartBinding.rvPoiItem.setVisibility(View.VISIBLE);

        if(null == poiAdapter){
            Log.d("得到推荐2",suggestionInfos.toString());
            startActivityViewModel.suggestionResultToPoiList(suggestionInfos);
            poiAdapter = new PoiAdapter(
                    startActivityViewModel.getStartPoiListLiveData().getValue());
//            activityStartBinding.rvPoiItem.setAdapter(poiAdapter);
        }else {
            Log.d("得到推荐3",suggestionInfos.toString());

            startActivityViewModel.suggestionResultToPoiList(suggestionInfos);
            poiAdapter.updateData(
                    startActivityViewModel.getStartPoiListLiveData().getValue());
        }
    }


}
